package com.kk.license.server.util;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @Description 使用Java自带keytool执行证书生成命令
 * @Author wangkang
 * @Create 2023-07-18 11:18
 * @Version 1.0
 */
@Slf4j
public class KeytoolUtils {
    /**
     * 生成证书路径,默认为当前程序目录下
     */
    public static final String PATH = System.getProperty("user.dir");

    /**
     * 生成私钥命令
     */
    private static String privateKeyCommand = "keytool -genkeypair -keysize 1024 -validity 3650 -alias \"privateKey\" -keystore \"" + PATH + "\\privateKeys.keystore\" -storepass \"public-password-bDq1BUKu6lQdWQj\" -keypass \"private-password-2fZULeK8K6Wk2g7\" -dname \"CN=localhost, OU=localhost, O=localhost, L=SH, ST=SH, C=CN\"";
    /**
     * 导出公钥命令
     */
    private static String certfileCommand = "keytool -exportcert -alias \"privateKey\" -keystore \"" + PATH + "\\privateKeys.keystore\" -storepass \"public-password-bDq1BUKu6lQdWQj\" -file \"" + PATH + "\\certfile.cer\"";
    /**
     * 生成公钥命令
     */
    private static String publicKeyCommand = "keytool -import -alias \"publicCert\" -file \"" + PATH + "\\certfile.cer\" -keystore \"" + PATH + "\\publicCerts.keystore\" -storepass \"public-password-bDq1BUKu6lQdWQj\" -noprompt";

    /**
     * 生成私钥
     */
    public static void generatePrivateKey() {
        log.info("开始生成私钥库");
        try {
            exec(privateKeyCommand);
            log.info("私钥生成成功");
        } catch (Exception e) {
            log.error("{}", e);
        }
    }

    /**
     * 导出公钥
     */
    public static void generateCertFile() {
        log.info("开始将公钥导出至临时文件");
        try {
            exec(certfileCommand);
            log.info("公钥证书生成成功");
        } catch (Exception e) {
            log.error("{}", e);
        }
    }

    /**
     * 生成公钥
     */
    public static void generatePublicKey() {
        log.info("开始将文件导入到公钥库");
        try {
            exec(publicKeyCommand);
            log.info("公钥证书生成成功");
        } catch (Exception e) {
            log.error("{}", e);
        }
    }

    private static void exec(String s) throws IOException {
        Runtime runtime = Runtime.getRuntime();
        BufferedReader br = new BufferedReader(
                new InputStreamReader(
                        runtime.exec(s).getInputStream(), "GB2312"
                )
        );
        String line;
        StringBuilder b = new StringBuilder();
        while ((line = br.readLine()) != null) {
            b.append(line).append("\n");
        }
        log.info(b.toString());
    }
}
